#!/bin/env python3
import argparse
import os
import sys

PREFIX = "emacs-"
PREFIX_LEN = len(PREFIX)
config = []

def initialize():
	for dir in os.listdir(os.path.expanduser("~/configs/")):
		if dir.startswith(PREFIX):
			config.append(dir[PREFIX_LEN:])


def show_configs():
	for c in config:
		print(c)


def choose_one(name):
	if config.count(name) != 0:
		do_link(name)
	else:
		print("配置%s不存在" %(name))


def do_link(name):
	target = os.path.expanduser("~/.emacs.d")
	if os.path.exists(target):
		if not os.path.islink(target) and os.path.isdir(target):
			ans = input("已存在目录.emacs.d，确认删除该目录并修改配置方案？[Y/N]")
			if ans.upper() == 'Y':
				os.removedirs(target) 
			else:
				return
		else:
			os.remove(target)

	src = os.path.join(os.path.expanduser("~/configs/"), PREFIX + name)
	os.symlink(src, target)


def show_current():
	try:
		target = os.readlink(os.path.expanduser("~/.emacs.d"))
		print(os.path.basename(target)[PREFIX_LEN:])
	except FileNotFoundError as e:
		print("未指定")

if __name__ == "__main__":
	initialize()

	parser = argparse.ArgumentParser(description="切换emacs配置")
	parser.add_argument("-l", "--list", action="store_true", help="列出可选emacs配置方案")
	parser.add_argument("-C", "--current", action="store_true", help="显示当前emacs配置方案")
	parser.add_argument("-c", "--choose", nargs=1, help="选择emacs配置方案")
	args = parser.parse_args(sys.argv[1:])

	if args.list:
		show_configs()

	if args.current:
		show_current()

	if args.choose is not None:
		choose_one(args.choose[0])
